package com.zy.algorithm.v3.sort

import com.zy.view.DIYSortView
import com.zy.utils.DataBuildUtils
import com.zy.utils.data.Point
import com.zy.utils.data.Point.Companion.ASS_INDEX
import com.zy.utils.data.auto.AutoIndexElement
import com.zy.utils.data.auto.AutoNodeStep
import com.zy.utils.data.auto.Coordinate
import java.util.ArrayList

class CountSortFragment : BaseV3SortFragment() {

    private var array = intArrayOf(5, 5, 9, 9, 8, 3, 4, 6, 3, 9, 2, 6, 4, 7, 1, 4, 2, 7, 8, 1)

    override fun setSortData(diyV4: DIYSortView) {
        diyV4.setD(100)
        diyV4.addPoint(2, 1, "V")
        val assistArray = intArrayOf(
            1, 2, 3, 4, 5, 6, 7, 8, 9
        )
        diyV4.addNoMoveAssistList(7, 8, assistArray, Point.Type.ASSIST)

        if (code == 0) {
            array = DataBuildUtils.getRandomSortArray(20, 9)
            diyV4.create(2, 2, array, Point.Type.DEFAULT)
        } else {
            diyV4.create(2, 2, array, Point.Type.DEFAULT)
        }
    }

    var hasMove = false
    override fun autoMove(diyV4: DIYSortView) {
        super.autoMove(diyV4)

        if (hasMove) {
            autoBackSort(diyV4)
            return
        }

        hasMove = true

        val baseX = 6
        val list: MutableList<AutoNodeStep> = ArrayList<AutoNodeStep>()

        val baseY = intArrayOf(7, 7, 7, 7, 7, 7, 7, 7, 7)

        var baseAssBaseX = 2
        array.forEachIndexed { index, v ->
            val autoIndexElement = AutoIndexElement(index, Coordinate(baseX + v, baseY[v - 1]--))
            val assElement = AutoIndexElement(ASS_INDEX, Coordinate(++baseAssBaseX, 1))
            list.add(AutoNodeStep(listOf(autoIndexElement, assElement)))
        }
        diyV4.autoMove(list)
    }


    var hasBackSort = false
    private fun autoBackSort(diyV4: DIYSortView) {
        if (hasBackSort) {
            return
        }
        hasBackSort = true
        diyV4.autoSortByV(2, 3, 1..9)
    }
}